require("../@babel/runtime/helpers/interopRequireDefault")(require("md5.js"));

var t = require("wx-promise-request"), e = getApp();




const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  // return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
  return [year, month, day].map(formatNumber).join('')
}


Date.prototype.Format = function(fmt) { //author: meizz
  var o = {
    "M+": this.getMonth() + 1, //月份
    "d+": this.getDate(), //日
    "h+": this.getHours(), //小时
    "m+": this.getMinutes(), //分
    "s+": this.getSeconds(), //秒
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度
    "S": this.getMilliseconds() //毫秒
  };
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  return fmt;
};



const formatNum = num => {
  var AA = new Array("零", "一", "二", "三", "四", "五", "六", "七", "八", "九");
  var BB = new Array("", "十", "百", "千", "万", "亿", "点", "");
  var a = ("" + num).replace(/(^0*)/g, "").split("."),
    k = 0,
    re = "";
  for (var i = a[0].length - 1; i >= 0; i--) {
    switch (k) {
      case 0:
        re = BB[7] + re;
        break;
      case 4:
        if (!new RegExp("0{4}\\d{" + (a[0].length - i - 1) + "}$").test(a[0]))
          re = BB[4] + re;
        break;
      case 8:
        re = BB[5] + re;
        BB[7] = BB[5];
        k = 0;
        break;
    }
    if (k % 4 == 2 && a[0].charAt(i + 2) != 0 && a[0].charAt(i + 1) == 0) re = AA[0] + re;
    if (a[0].charAt(i) != 0) re = AA[a[0].charAt(i)] + BB[k % 4] + re;
    k++;
  }
  if (a.length > 1) //加上小数部分(如果有小数部分) 
  {
    re += BB[6];
    for (var i = 0; i < a[1].length; i++) re += AA[a[1].charAt(i)];
  }
  console.log(re.length)
  if (re.length == 2 && re.charAt(0) == '一') {
    re = re.substring(1, re.length);
  }
  return re;
}


const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

var mathRound = function(val) {
  return Math.round(val);
}

// 高亮
var highLight = function (key, word) {
  var arr = [];
  highLightTemp(key, word, arr);
  return arr;
}

var highLightTemp = function (key, word, arr) {
  var index = word.indexOf(key);
  // 未查到
  if (!key || index == -1) {
    arr.push({
      key: false,
      str: word
    });
    return;
  }

  // 查到
  if (index == 0) {
    arr.push({
      key: true,
      str: key
    });

    if (word.length > key.length) {
      word = word.substring(key.length, word.length);
      highLightTemp(key, word, arr);
    }
  } else if (index != 0) {
    var _word = word.substring(0, index);
    arr.push({
      key: false,
      str: _word
    });
    word = word.substring(index, word.length);
    highLightTemp(key, word, arr);
  }

  return;
}

// 根据搜索字分割字符
var hilight_word = function (key, word) {
  let idx = word.indexOf(key),
    t = [];

  if (idx > -1) {
    if (idx == 0) {
      t = this.hilight_word(key, word.substr(key.length));
      t.unshift({
        key: true,
        str: key
      });
      return t;
    }

    if (idx > 0) {
      t = this.hilight_word(key, word.substr(idx));
      t.unshift({
        key: false,
        str: word.substring(0, idx)
      });
      return t;
    }
  }
  return [{
    key: false,
    str: word
  }];
}


/**
 * 数组去重
 */
var arrayUnique = function(arr) {
  var result = [],
    hash = {};
  for (var i = 0, elem;
    (elem = arr[i]) != null; i++) {
    if (!hash[elem]) {
      result.push(elem);
      hash[elem] = true;
    }
  }
  return result;
}

//根据关键词截取字符串
var strSub = function(str,key,flag){
  if(str.indexOf(key) != -1){
    if(flag){
      str = str.substr(str.lastIndexOf(key)+6, str.length);
    }else{
      str = str.substr(0,str.lastIndexOf(key));
    }
    return str;
  }
  return str;

}

//防止重复tij
var preventClick = function buttonClicked(self) {
  self.setData({
    buttonClicked: true
  })
  setTimeout(function () {
    self.setData({
      buttonClicked: false
    })
  }, 500)
}


//将毫秒转成秒
var millsecond2second = function(millsecond){
  var time = Math.ceil(parseFloat(millsecond) / 1000);  
  return time;
}

//添加积分
var addScore = function(fid,uid,scoreType,rname){
  wx.request({
    url: 'https://videoshequ3.chaoxing.com/api/addScore',
    method: 'POST',
    header: {
      'content-type': 'application/x-www-form-urlencoded' // 默认值
    },
    data: {
      'fid' : fid, //每个单位暂时写死
      'uid' : uid,
      'scoreType' : scoreType,
      'scoreDomain' : 'scoreshequ3.chaoxing.com', //每个单位可以写死
      'rname' : rname
    },
    success: function(res){
      console.log(res)
    },
    fail: function(){
      console.log("添加积分异常")
    }
  })
}

var setTimes = function setTimes(value) {
  var theTime = parseInt(value);//秒
  var theTime1 = 0;//分
  var theTime2 = 0;//时
  if (theTime > 60) {
    theTime1 = parseInt(theTime / 60);
    theTime = parseInt(theTime % 60);
    if (theTime1 > 60) {
      theTime2 = parseInt(theTime1 / 60);
      theTime1 = parseInt(theTime1 % 60);
    }
  };
  var theTime_y = parseInt(theTime);
  if (theTime_y < 10) {
    theTime_y = '0' + theTime_y
  }
  var results = "" + theTime_y;
  if (theTime1 > 0 || theTime1 == 0) {
    var theTime1_y = parseInt(theTime1);
    if (theTime1_y < 10) {
      theTime1_y = '0' + theTime1_y;
    }
    results = "" + theTime1_y + "分" + results + "秒";
  }
  if (theTime2 > 0 || theTime2 == 0) {
    var theTime2_y = parseInt(theTime2);
    if (theTime2_y < 10) {
      theTime2_y = '0' + theTime2_y;
    }
    results = "" + theTime2_y + "时" + results;
  }
  return results;
};

/**
 * 图片加载错误触发的事件
 */
var errorFunction = function errorFunction(e) {
  if (e.type == "error") {
    var errorImgIndex = e.target.dataset.errorimg //获取错误图片循环的下标
    var imgList = this.data.imgArr                 //将图片列表数据绑定到变量
    imgList[errorImgIndex] = this.data.defaultImg //错误图片替换为默认图片
    this.setData({
      imgArr: imgList
    })
  }
}

export function getCurrentPageUrlWithArgs() {
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  const url = currentPage.route
  const options = currentPage.options
  let urlWithArgs = `/${url}?`
  for (let key in options) {
    const value = options[key]
    urlWithArgs += `${key}=${value}&`
  }
  urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1)
  return urlWithArgs
}

export function getPrevPage(){
  
  var pages = getCurrentPages();
  var prevPage = pages[pages.length - 2];  //上一个页面
  const url = prevPage.route;
  const options = prevPage.options
  let urlWithArgs = `/${url}?`
  for (let key in options) {
    const value = options[key]
    urlWithArgs += `${key}=${value}&`
  }
  urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1)
  return urlWithArgs
}

// 时间展示
var formatSeconds = function formatSeconds(value) {
  var secondTime = parseInt(value); // 秒
  var minuteTime = 0; // 分
  var hourTime = 0; // 小时
  if (secondTime > 60) { //如果秒数大于60，将秒数转换成整数
    //获取分钟，除以60取整数，得到整数分钟
    minuteTime = parseInt(secondTime / 60);
    //获取秒数，秒数取佘，得到整数秒数
    secondTime = parseInt(secondTime % 60);
    //如果分钟大于60，将分钟转换成小时
    if (minuteTime > 60) {
      //获取小时，获取分钟除以60，得到整数小时
      hourTime = parseInt(minuteTime / 60);
      //获取小时后取佘的分，获取分钟除以60取佘的分
      minuteTime = parseInt(minuteTime % 60);
    }
  }
  var result;
  //时间的展示方式为00:00
  if (secondTime < 10) {
    result = "0" + parseInt(secondTime);
  } else {
    result = "" + parseInt(secondTime);
  }
  if (minuteTime > 0) {
    if (minuteTime < 10) {
      result = "0" + parseInt(minuteTime) + ":" + result;
    } else {
      result = "" + parseInt(minuteTime) + ":" + result;
    }
  } else {
    result = "00:" + result;
  }
  //由于限制时长最多为三分钟,小时用不到
  if (hourTime > 0) {
    result = "" + parseInt(hourTime) + ":" + result;
  }
  return result;
}







function n() {
    return new Promise(function(t, e) {
        wx.login({
            success: function(e) {
                var n = e.code;
                t(n), console.log("code值" + n);
            },
            fail: function(t) {
                wx.hideLoading(), wx.showModal({
                    title: "网络繁忙，请稍后再试",
                    showCancel: !1
                }), e(t), console.info(t);
            }
        });
    });
}

function a(t) {
    return console.log(e.globalData.baseUrl + "api/users/appletlogin"), new Promise(function(n, a) {
        wx.request({
            url: e.globalData.baseUrl + "api/users/appletlogin",
            data: {
                p: "w",
                code: t
            },
            method: "POST",
            header: {
                Accept: "application/json"
            },
            success: function(t) {
                // console.log("token值" + t.data.data.api_token);
                // var a = t.data.data.api_token;
                // wx.setStorage({
                //     key: "api_token",
                //     data: a
                // }), e.globalData.api_token = a, n(a);
            },
            fail: function(t) {
                wx.showModal({
                    title: "服务器繁忙，请稍后再试",
                    showCancel: !1
                }), a(t);
            }
        });
    });
}

function r(t) {
    return new Promise(function(n, a) {
        wx.request({
            url: e.globalData.baseUrl + "antique3d/front/api/users/info",
            data: {
                p: "w",
                api_token: t
            },
            method: "GET",
            header: {
                Accept: "application/json"
            },
            success: function(t) {
                console.log(e.globalData.api_token), null != t.data.data.avatar && (e.globalData.avatar = t.data.data.avatar, 
                e.globalData.nickName = t.data.data.nickname), n(t);
            },
            fail: function(t) {
                wx.hideLoading(), a(0);
            }
        });
    });
}

(0, t.setConfig)({
    concurrency: 5
});

var o = "";

module.exports = {
    httpPost: function(e, n) {
        return n.p || (n.p = "w"), (0, t.request)({
            url: e,
            data: n,
            header: {
                Accept: "application/json"
            },
            method: "POST"
        });
    },
    httpGet: function(e, n) {
        return n.p || (n.p = "w"), (0, t.request)({
            url: e,
            data: n,
            header: {
                Accept: "application/json"
            },
            method: "GET"
        });
    },
    unique: function(t) {
        var e = {};
        return t.forEach(function(t) {
            e[JSON.stringify(t)] = 1;
        }), t = Object.keys(e).map(function(t) {
            return JSON.parse(t);
        });
    },
    formatTime: function(t) {
        var e = t.getHours(), n = t.getMinutes(), a = t.getSeconds();
        return e < 10 && (e = "0" + e), n < 10 && (n = "0" + n), a < 10 && (a = "0" + a), 
        e + ":" + n + ":" + a;
    },
    format: function(t) {
        var e;
        return t = t.split(":"), e = 60 * parseInt(t[0]) * 60, e += 60 * parseInt(t[1]), 
        e += parseInt(t[2]);
    },
    reverseFormat: function(t) {
        var e = parseInt(t), n = 0, a = 0;
        return e > 59 && (n = parseInt(e / 60), e = parseInt(e % 60), n > 59 && (a = parseInt(n / 60), 
        n = parseInt(n % 60))), parseInt(a) < 10 && (a = "0" + a), parseInt(n) < 10 && (n = "0" + n), 
        parseInt(e) < 10 && (e = "0" + e), a + ":" + n + ":" + e;
    },
    audioBackTime: function(t) {
        return 3600 * (t = t.split(":"))[0] + 60 * t[1] + parseInt(t[2]);
    },
    audioTime: function(t) {
        var e = "";
        if (t > -1) {
            var n = Math.floor(t / 60), a = t % 60;
            n < 10 && (e = "0"), e += n + ":", a < 10 && (e += "0"), e += a.toFixed(0);
        }
        return e;
    },
    preventclick: function(t) {
        return "" == o ? (o = new Date().getTime(), !0) : new Date().getTime() - o > t && (o = new Date().getTime(), 
        !0);
    },
    random: function() {
        for (var t = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678", e = t.length, n = "", a = 0; a < 16; a++) n += t.charAt(Math.floor(Math.random() * e));
        return n;
    },
    compareVersion: function(t, e) {
        t = t.split("."), e = e.split(".");
        for (var n = Math.max(t.length, e.length); t.length < n; ) t.push("0");
        for (;e.length < n; ) e.push("0");
        for (var a = 0; a < n; a++) {
            var r = parseInt(t[a]), o = parseInt(e[a]);
            if (r > o) return 1;
            if (r < o) return -1;
        }
        return 0;
    },
    tranNumber: function(t, e) {
        e = e || 2;
        var n = t.toString();
        if (n.length < 5) return n;
        if (n.length > 8) {
            var a = n.substring(n.length - 8, n.length - 8 + e);
            return parseFloat(parseInt(t / 1e8) + "." + a) + "亿";
        }
        if (n.length > 4) {
            var r = n.substring(n.length - 4, n.length - 4 + e);
            return parseFloat(parseInt(t / 1e4) + "." + r) + "万";
        }
    },
    userLogin: function() {
        n().then(function(t) {
            return a(t);
        }).then(function(t) {
            return r(t);
        });
    },
    wxLogin: n,
    appLogin: a,
    getUserInfo: r,
	formatTime: formatTime,
  mathRound: mathRound,
  hilight_word: hilight_word,
  highLight: highLight,
  arrayUnique: arrayUnique,
  formatNum: formatNum,
  strSub: strSub,
  preventClick: preventClick,
  millsecond2second: millsecond2second,
  setTimes: setTimes,
  addScore: addScore,
  errorFunction: errorFunction,
  getCurrentPageUrlWithArgs : getCurrentPageUrlWithArgs,
  getPrevPage : getPrevPage,
  formatSeconds: formatSeconds
};








